package suanzi.core.db.controller;


import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import suanzi.core.db.DB.DBContextHolder;
import suanzi.core.db.DB.DynamicDataSource;
import suanzi.core.db.entity.BaseItemEntity;
import suanzi.core.db.entity.SysDatabase;
import suanzi.core.db.service.BaseItemService;
import suanzi.core.db.service.ISysDataBaseService;

import javax.annotation.Resource;
import java.util.List;


/**
 * 数据库实例
 *
 * @author admin
 * @email admin@gmail.com
 * @date 2021-05-25 18:56:39
 */
@RestController
@RequestMapping("")
@Slf4j
public class DatebaseController {
    @Resource
    private ISysDataBaseService dataBaseService;
    @Autowired
    private BaseItemService baseItemService;
    @Autowired
    private DynamicDataSource dynamicDataSource;
    /**
     * 列表
     */
    @PostMapping("/get")
    public List<BaseItemEntity> get(@RequestParam String companyId) throws Exception {
        if (StringUtils.isNotEmpty(companyId)) {
            //默认切换到主数据源,进行整体资源的查找
            DBContextHolder.clearDataSource();
            SysDatabase dataBase = dataBaseService.getDateSourceCache(companyId);
            log.info("url=====" + dataBase.getIp());
            log.info("getDatabasename=====" + dataBase.getDatebasename());

            dynamicDataSource.createDataSourceWithCheck(dataBase);
            //切换到该数据源
            DBContextHolder.setDataSource(dataBase.getDatebasename());
        }
        System.out.println("查询开始");
        List<BaseItemEntity> list = baseItemService.listAll();
        System.out.println("查询结束");

        return  list;
    }
    /**
     * 列表
     */
    @PostMapping("/list")
    public List<BaseItemEntity> list() throws Exception {
        System.out.println("查询开始");
        List<BaseItemEntity> list = baseItemService.listAll();
        System.out.println("查询结束");

        return  list;
    }

}
